﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OpenMms.Common.Auth;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace OpenMms.MVC.Areas.User.Controllers
{
    /// <summary>
    ///登录验证过滤
    /// </summary>
    public class BaseController : Controller
    {
        protected IAuth _auth;
        public const string Token = "Token";

        public BaseController(IAuth auth) => this._auth = auth;

        //表示是否检查登录
        /// <summary>
        /// 是否启用过滤器
        /// </summary>
        public bool IsCheck { get; set; }

        /// <summary>
        /// Action方法执行之前执行此方法
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var token = "";

            //Token by QueryString
            var request = filterContext.HttpContext.Request;
            if (request.Cookies[Token] != null)  //从Cookie读取Token
            {
                token = request.Cookies[Token];
            }

            if (string.IsNullOrEmpty(token))
            {
                //直接登录
                filterContext.Result = LoginResult("");
                return;
            }
            //验证
            if (_auth.CheckLogin(token, request.Path) == false)
            {
                //会话丢失，跳转到登录页面
                filterContext.Result = LoginResult("");
                return;
            }

            base.OnActionExecuting(filterContext);
        }

        public virtual ActionResult LoginResult(string username) => new RedirectResult("/Login/Index");
    }
}